<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="商品编码" prop="name">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in goodTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in putOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:good:add']"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="goodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品编码" align="center" prop="code"/>
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="权重" align="center" prop="chance"/>
      <el-table-column label="成本价格" align="center" prop="price"/>
      <el-table-column label="销售价格" align="center" prop="money"/>
      <!--<el-table-column label="品牌" align="center" prop="brand"/>-->
      <el-table-column label="商品类型" align="center" prop="type" :formatter="typeFormat"/>
      <el-table-column label="库存" align="center" prop="stock"/>
      <el-table-column label="上架状态" align="center" prop="status" :formatter="putFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status==1"
            v-hasPermi="['system:good:edit']"
          >修改
          </el-button>


          <el-button
            size="mini"
            type="text"
            @click="handlePut(scope.row)"
            v-if="scope.row.status==1"
          >上架
          </el-button>

          <el-button
            size="mini"
            type="text"
            @click="handlePut(scope.row)"
            v-if="scope.row.status==2"
          >下架
          </el-button>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status==1"
            v-hasPermi="['system:good:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="code" >
              <el-input v-model="form.code" placeholder="请输入商品编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name" >
              <el-input v-model="form.name" placeholder="请输入商品名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品类型" >
              <el-select v-model="form.type" placeholder="请选择商品类型" prop="type1">
                <el-option
                  v-for="dict in goodTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权重" prop="chance" >
              <el-input-number v-model="form.chance" :min="0" :precision="0" max="10000000" placeholder="请输入权重"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock" >
              <el-input-number v-model="form.stock" :min="0" :precision="0" max="10000000" placeholder="请输入库存"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成本价格" prop="price" >
              <el-input-number v-model="form.price" :min="0" :precision="2" max="10000000"  placeholder="请输入成本价格"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售价格" prop="money" >
              <el-input-number v-model="form.money" :min="0"  :precision="2" max="10000000" placeholder="请输入销售价格"/>
            </el-form-item>
          </el-col>
         <!-- <el-col :span="24">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" type="textarea" placeholder="请输入品牌"/>
            </el-form-item>
          </el-col>-->
          <el-col :span="24" >
            <el-form-item label="商品图标" prop="image" >
              <el-upload
                class="upload-demo"
                accept="image/jpeg,image/png"
                :action="url"
                :on-success="onSuccessImage	"
                :headers="headers"
                list-type="picture-card"
                :on-remove="handleRemoveImage"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="form.files">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品轮播图" prop="fileList" >
              <el-upload
                class="upload-demo"
                accept="image/jpeg,image/png"
                :action="url"
                :on-success="onSuccess	"
                :headers="headers"
                list-type="picture-card"
                :on-remove="handleRemove"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                :file-list="form.fileList">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品详情" prop="detail">
              <Editor v-model="form.detail"  />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listGood, getGood, delGood, addGood, updateGood, exportGood} from "@/api/system/good";
  import {getToken} from "@/utils/auth.js";
  import Editor from '@/components/Editor';
  export default {
    components: {
      Editor
    },
    name: "Good",
    data() {
      return {
        headers:{
          'Authorization': null
        },
        url:null,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 商品表格数据
        goodList: [],
        //商品类型
        goodTypeOptions: [],
        // 上架状态
        putOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          code: undefined,
          pics: undefined,
          image: undefined,
          detail: undefined,
          chance: undefined,
          price: undefined,
          brand: undefined,
          type: undefined,
          status: undefined,
          stock: undefined,
          money: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          code: [{max: 20, message: '编码不能超过20个字符', trigger: 'blur'}, { required: true, message: "编码不能为空", trigger: "blur" }],
          name : [ {max: 20, message: '编码不能超过20个字符', trigger: 'blur'},{ required: true, message: "名称不能为空", trigger: "blur" }],
          chance: [ { required: true, message: "权重不能为空", trigger: "blur" }],
          stock: [ { required: true, message: "库存不能为空", trigger: "blur" }],
          type1: [ { required: true, message: "类型不能为空", trigger: "blur" }],
          image: [ { required: true, message: "图标不能为空", trigger: "blur" }],
          fileList: [ { required: true, message: "轮播图不能为空", trigger: "blur" }],
        }
      };
    },
    created() {
      this.getList();
      this.getUrl();
      this.getDicts("sys_good_type").then(response => {
        this.goodTypeOptions = response.data;
      });
      this.getDicts("sys_put").then(response => {
        this.putOptions = response.data;
      });
    },
    methods: {
      putFormat(row, column) {
        return this.selectDictLabel(this.putOptions, row.status);
      },
      typeFormat(row, column) {
        return this.selectDictLabel(this.goodTypeOptions, row.type);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      getUrl(){
        let url =   process.env.VUE_APP_BASE_API+'/common/createOSS'
        this.url = url
        this.headers.Authorization ='Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      },
      handleRemove(file, fileList) {
        this.form.fileList.forEach((item, i) => {
          if(item.url===file.url) {
            this.form.fileList.splice(i, 1)
          }
        })
      },
      onSuccess(response, file, fileList){
        let obj={};
        obj.url=file.response.url;
        this.form.fileList.push(obj);
      },
      onSuccessImage(response, file, fileList){
        this.form.image=file.response.url;
      },
      handleRemoveImage(file, fileList) {
        this.form.image=undefined;
      },
      /** 查询商品列表 */
      getList() {
        this.loading = true;
        listGood(this.queryParams).then(response => {
          this.goodList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          goodId: undefined,
          name: undefined,
          code: undefined,
          pics: undefined,
          image: undefined,
          detail: undefined,
          chance: undefined,
          price: undefined,
          brand: undefined,
          type: undefined,
          status: "0",
          stock: undefined,
          money: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          fileList:[],
          files:[]
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.goodId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加商品";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const goodId = row.goodId || this.ids
        getGood(goodId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改商品";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.goodId != undefined) {
              updateGood(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addGood(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const goodIds = row.goodId || this.ids;
        this.$confirm('是否确认删除商品编号为"' + goodIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delGood(goodIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 上下架操作 */
      handlePut(row) {
        var str=row.status==1?"上架":"下架";
        var _this=this;
        this.$confirm("是否确认"+str+row.name+"商品?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          var data={};
          data.goodId=row.goodId;
          data.status=row.status==1?2:1;
          updateGood(data).then(response => {
            if (response.code === 200) {
              _this.msgSuccess("操作成功");
              _this.getList();
            } else {
              _this.msgError(response.msg);
            }
          });
        }).then(() => {
          // this.getList();
          // this.msgSuccess("操作成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有商品数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportGood(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      }
    }
  };
</script>
